/*
 * StringUtils.java
 * 
 * Created on 30.9.2007, 23:14:21
 * 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package eu.easyedu.dictionary.api.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author hlavki
 */
public class StringUtils {

    private static final Logger log = Logger.getLogger(StringUtils.class.getName());

    private static final String toString(String alias, Object obj, StringBuffer sb) {
        if (obj == null) {
            return "";
        }
        try {
            BeanInfo info = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
            for (int i = 0; i < descriptors.length; i++) {
                PropertyDescriptor descriptor = descriptors[i];
                if (descriptor.getPropertyType() == null ||
                        Collection.class.isAssignableFrom(descriptor.getPropertyType())) {
                    log.fine("collection handling not supported: skipping property: " + descriptor.getName());
                    continue;
                }
                if (descriptor.getReadMethod().getDeclaringClass().equals(Object.class)) {
                    log.fine("property defined on Object class: skipping: " + descriptor.getName());
                    continue;
                }
                Object value = descriptor.getReadMethod().invoke(obj, (Object[]) null);
                if (value == null) {
                    log.fine("property value is null: skipping: " + descriptor.getName());
                    continue;
                }
                Class returnType = descriptor.getReadMethod().getReturnType();
                if (!returnType.isPrimitive() && !returnType.getName().startsWith("java.") &&
                        !returnType.isEnum()) {
                    log.fine("property is unknown type or not primitive [" + returnType.getName() + "]");
                    String simpleName = returnType.getName().substring(returnType.getName().lastIndexOf('.') + 1);
                    sb.append(alias).append(".").append(descriptor.getName()).append(" = new ").append(simpleName).append("()\n");
                    toString(alias + "." + descriptor.getName(), value, sb);
                    continue;
                }
                sb.append(alias).append(".").append(descriptor.getName()).append(" = ").append(value).append('\n');
            }
        } catch (Exception e) {
            log.log(Level.SEVERE, "hql example criterion building error", e);
            return null;
        }
        return sb.toString();
    }

    public static final String toString(String alias, Object obj) {
        return toString(alias, obj, new StringBuffer());
    }
}
